#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gitee SSH Key Generator
生成Gitee SSH公钥的Python脚本

使用方法:
python generate_gitee_ssh_key.py
"""

import os
import subprocess
import sys
import platform
from pathlib import Path


class GiteeSSHKeyGenerator:
    def __init__(self):
        self.ssh_dir = Path.home() / '.ssh'
        self.key_name = 'id_ed25519'
        self.private_key_path = self.ssh_dir / self.key_name
        self.public_key_path = self.ssh_dir / f'{self.key_name}.pub'
        
    def check_ssh_directory(self):
        """检查并创建SSH目录"""
        if not self.ssh_dir.exists():
            print(f"创建SSH目录: {self.ssh_dir}")
            self.ssh_dir.mkdir(mode=0o700, parents=True)
            return True
        return False
    
    def check_existing_keys(self):
        """检查是否已存在SSH密钥"""
        if self.private_key_path.exists() or self.public_key_path.exists():
            print("⚠️  检测到已存在的SSH密钥:")
            if self.private_key_path.exists():
                print(f"   私钥: {self.private_key_path}")
            if self.public_key_path.exists():
                print(f"   公钥: {self.public_key_path}")
            
            choice = input("\n是否覆盖现有密钥? (y/N): ").strip().lower()
            return choice in ['y', 'yes', '是']
        return True
    
    def generate_ssh_key(self, comment="Gitee SSH Key", passphrase=""):
        """生成SSH密钥"""
        try:
            print(f"\n🔑 正在生成SSH密钥...")
            print(f"   类型: ed25519")
            print(f"   注释: {comment}")
            print(f"   保存位置: {self.private_key_path}")
            
            # 构建ssh-keygen命令
            cmd = [
                'ssh-keygen',
                '-t', 'ed25519',
                '-C', comment,
                '-f', str(self.private_key_path),
                '-N', passphrase  # 空密码
            ]
            
            # 执行命令
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                check=True
            )
            
            print("✅ SSH密钥生成成功!")
            return True
            
        except subprocess.CalledProcessError as e:
            print(f"❌ SSH密钥生成失败: {e}")
            print(f"错误输出: {e.stderr}")
            return False
        except FileNotFoundError:
            print("❌ 未找到ssh-keygen命令")
            print("请确保已安装OpenSSH或Git Bash")
            return False
    
    def list_ssh_files(self):
        """列出SSH目录中的文件"""
        print(f"\n📁 SSH目录内容 ({self.ssh_dir}):")
        try:
            ssh_files = list(self.ssh_dir.glob('*'))
            if ssh_files:
                for file in sorted(ssh_files):
                    file_type = "目录" if file.is_dir() else "文件"
                    print(f"   {file.name} ({file_type})")
            else:
                print("   (空目录)")
        except Exception as e:
            print(f"   无法读取目录: {e}")
    
    def read_public_key(self):
        """读取并显示公钥内容"""
        try:
            if self.public_key_path.exists():
                with open(self.public_key_path, 'r', encoding='utf-8') as f:
                    public_key = f.read().strip()
                
                print(f"\n🔓 SSH公钥内容:")
                print("=" * 60)
                print(public_key)
                print("=" * 60)
                
                # 提供复制提示
                print("\n📋 请复制上面的公钥内容到Gitee的SSH公钥设置中")
                print("   Gitee设置路径: 设置 -> SSH公钥 -> 添加公钥")
                
                return public_key
            else:
                print(f"❌ 公钥文件不存在: {self.public_key_path}")
                return None
                
        except Exception as e:
            print(f"❌ 读取公钥失败: {e}")
            return None
    
    def get_key_fingerprint(self):
        """获取密钥指纹"""
        try:
            cmd = ['ssh-keygen', '-lf', str(self.public_key_path)]
            result = subprocess.run(cmd, capture_output=True, text=True, check=True)
            fingerprint = result.stdout.strip()
            print(f"\n🔍 密钥指纹:")
            print(f"   {fingerprint}")
            return fingerprint
        except Exception as e:
            print(f"⚠️  无法获取密钥指纹: {e}")
            return None
    
    def save_to_file(self, public_key, filename="gitee_public_key.txt"):
        """将公钥保存到文件"""
        try:
            output_file = Path(filename)
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(public_key)
            print(f"\n💾 公钥已保存到: {output_file.absolute()}")
            return True
        except Exception as e:
            print(f"❌ 保存公钥失败: {e}")
            return False
    
    def run(self):
        """运行主程序"""
        print("🚀 Gitee SSH密钥生成器")
        print("=" * 40)
        
        # 检查系统
        print(f"操作系统: {platform.system()} {platform.release()}")
        
        # 检查SSH目录
        self.check_ssh_directory()
        
        # 检查现有密钥
        if not self.check_existing_keys():
            print("操作已取消")
            return False
        
        # 获取用户输入
        print("\n📝 请输入SSH密钥信息:")
        comment = input(f"注释 (默认: Gitee SSH Key): ").strip()
        if not comment:
            comment = "Gitee SSH Key"
        
        use_passphrase = input("是否设置密码保护? (y/N): ").strip().lower()
        passphrase = ""
        if use_passphrase in ['y', 'yes', '是']:
            passphrase = input("请输入密码: ")
        
        # 生成密钥
        if self.generate_ssh_key(comment, passphrase):
            # 列出文件
            self.list_ssh_files()
            
            # 显示公钥
            public_key = self.read_public_key()
            
            # 显示指纹
            self.get_key_fingerprint()
            
            # 询问是否保存到文件
            if public_key:
                save_choice = input("\n是否将公钥保存到文件? (Y/n): ").strip().lower()
                if save_choice not in ['n', 'no', '否']:
                    self.save_to_file(public_key)
            
            print("\n✅ SSH密钥生成完成!")
            print("\n📖 下一步操作:")
            print("1. 复制上面显示的公钥内容")
            print("2. 登录Gitee (https://gitee.com)")
            print("3. 进入 设置 -> SSH公钥")
            print("4. 点击 '添加公钥'")
            print("5. 粘贴公钥内容并保存")
            
            return True
        else:
            return False


def main():
    """主函数"""
    try:
        generator = GiteeSSHKeyGenerator()
        success = generator.run()
        
        if success:
            input("\n按回车键退出...")
        else:
            input("\n程序执行失败，按回车键退出...")
            sys.exit(1)
            
    except KeyboardInterrupt:
        print("\n\n操作已取消")
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ 程序执行出错: {e}")
        input("按回车键退出...")
        sys.exit(1)


if __name__ == "__main__":
    main() 